<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <div style="margin-bottom: 10px">
        <span style="color:gray; font-size:16px"> 时间范围: </span>
        <el-date-picker v-model="listQuery.timeInterval" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="mini" align="right">
        </el-date-picker>
      </div>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入用户ID" v-model="listQuery.userId">
      </el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="商品ID" v-model="listQuery.goodsId">
      </el-input>
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入订单编号" v-model="listQuery.orderSn">
      </el-input>
      <el-select clearable class="filter-item" style="width: 200px;" placeholder="请选择订单状态" v-model="listQuery.value">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" :loading="downloadLoading">导出</el-button>
      <el-badge :value="unShipOrder" :max="99" class="item">
        <el-button class="filter-item" type="warning" size="small" round style="margin-left:30px;" @click="queryUnShipOrder">待发货</el-button>
      </el-badge>
      <audio id="audio" src="https://oss-hong-yi.oss-cn-beijing.aliyuncs.com/180528.mp3"></audio>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row :default-sort="{prop: 'payTime', order: 'descending'}">

      <el-table-column align="center" min-width="100" label="订单编号" prop="orderSn" sortable>
      </el-table-column>

      <el-table-column align="center" label="用户ID" prop="userId" sortable>
      </el-table-column>

      <el-table-column align="center" label="订单状态" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag>{{scope.row.orderStatus | orderStatusFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="订单金额" prop="goodsPrice" min-width="250px">
        <template slot-scope="scope">
          {{"积分: " + scope.row.goodsIntegral + " 爱币: " + scope.row.goodsPrice}}
        </template>
      </el-table-column>

      <el-table-column align="center" label="支付金额" prop="actualPrice" min-width="250px">
        <template slot-scope="scope">
          {{"积分: " + scope.row.actualIntegral + " 爱币: "+scope.row.actualPrice}}
        </template>
      </el-table-column>

      <el-table-column align="center" label="赠送爱币" prop="givePrice">
      </el-table-column>

      <el-table-column align="center" label="支付时间" prop="payTime" sortable width="200px">
      </el-table-column>

      <el-table-column align="center" label="物流单号" prop="shipSn" width="200px">
      </el-table-column>

      <el-table-column align="center" label="物流渠道" prop="shipChannel">
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="primary" size="mini" @click="handleShip(scope.row)" v-if="scope.row.orderStatus==201">发货</el-button>
          <el-button type="primary" size="mini" @click="handleRefund(scope.row)" v-if="scope.row.orderStatus==202">退款</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 订单详情对话框 -->

    <el-dialog width="800px" :visible.sync="orderDialogVisible">
      <el-form id="orderDialog" :data="orderDetail" label-position="left">
        <h1 class="orderDialogtitle" style="text-align:center;">爱联商圈</h1>
        <h3>订单详情</h3>
        <el-form-item label="订单编号">
          <span>{{ orderDetail.order.orderSn }}</span>
        </el-form-item>
        <el-form-item label="订单状态">
          <template slot-scope="scope">
            <el-tag>{{orderDetail.order.orderStatus | orderStatusFilter}}</el-tag>
          </template>
        </el-form-item>
        <el-form-item label="订单用户">
          <span>用户名:{{ nickname }}</span>
          <span>,用户id:{{ orderDetail.order.userId }}</span>
        </el-form-item>
        <el-form-item label="收货信息">
          <span>（收货人）{{ orderDetail.order.consignee }}</span>
          <span>（手机号）{{ orderDetail.order.mobile }}</span>
          <span>（地址）{{ orderDetail.order.address }}</span>
        </el-form-item>
        <el-form-item label="商品信息">
          <el-table size="small" :data="orderDetail.orderGoods" border fit highlight-current-row>
            <el-table-column align="center" label="商品名称" width="145" prop="goodsName" />
            <el-table-column align="center" label="商品id" width="80" prop="goodsId" />
            <el-table-column align="center" label="货品规格" width="80" prop="specifications" />

            <el-table-column align="center" label="积分" width="75" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-label type="primary" size="mini" v-if="scope.row.integralFlag==2">赠送</el-label>
                <el-label type="primary" size="mini" v-if="scope.row.integralFlag==1">消费</el-label>
                <el-label type="primary" size="mini">{{scope.row.integral}}</el-label>
              </template>
            </el-table-column>

            <el-table-column align="center" label="爱币" width="75" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-label type="primary" size="mini" v-if="scope.row.priceFlag==1">消费</el-label>
                <el-label type="primary" size="mini" v-if="scope.row.priceFlag==2">赠送</el-label>
                <el-label type="primary" size="mini">{{scope.row.price}}</el-label>
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="积分" prop="integral" />
          <el-table-column align="center" label="爱币" prop="price" /> -->
            <el-table-column align="center" label="货品数量" width="50" prop="number" />
            <el-table-column align="center" label="货品图片" width="100" prop="picUrl">
              <template slot-scope="scope">
                <img :src="scope.row.picUrl" width="40" />
              </template>
            </el-table-column>
            <el-table-column align="center" label="备注" width="100" prop="remark" />
            <el-table-column  label="操作" width="50">
              <template slot-scope="scope">
                <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <!-- <el-form-item label="费用信息">
          <span>
          (实际费用){{ orderDetail.order.actualPrice }}元 =
          (商品总价){{ orderDetail.order.goodsPrice }}元 +
          (快递费用){{ orderDetail.order.freightPrice }}元 -
          (优惠减免){{ orderDetail.order.couponPrice }}元 -
          (积分减免){{ orderDetail.order.integralPrice }}元
          </span>
      </el-form-item> -->
        <el-form-item label="费用信息">
          <span>
            (积分){{ orderDetail.order.goodsIntegral }}分 + (爱币){{ orderDetail.order.goodsPrice }}爱币 + (快递费用){{ orderDetail.order.freightPrice }}爱币
          </span>
        </el-form-item>
        <el-form-item label="赠送信息">
          <span style="color:green">
            (积分){{ orderDetail.order.giveIntegral }}积分 + (爱币){{ orderDetail.order.givePrice }}爱币
          </span>
        </el-form-item>
        <el-form-item label="支付信息">
          <span>（支付渠道）钱包支付</span>
          <span>（支付时间）{{orderDetail.order.payTime }}</span>
        </el-form-item>
        <el-form-item label="快递信息">
          <span>（快递公司）{{ orderDetail.order.shipChannel }}</span>
          <span>（快递单号）{{ orderDetail.order.shipSn }}</span>
          <span>（发货时间）{{ orderDetail.order.shipTime }}</span>
        </el-form-item>
        <el-form-item label="收货信息">
          <span>（确认收货时间）{{ orderDetail.order.confirmTime }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" id="orderDialogOut" @click="orderDialogsee()">预览</el-button>
        <el-button type="primary" id="orderDialogOut" @click="orderDialogOut()">打印</el-button>
      </div>
    </el-dialog>

    <el-dialog title=编辑备注 :visible.sync="dialogFormVisibles">
      <el-form ref="editForm" :model="editForm" status-icon label-position="right" style='width: 500px; margin-left:50px;'>
        <el-form-item label="备注" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取消</el-button>
        <el-button type="primary" @click="exchangeData">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发货" :visible.sync="shipDialogVisible" width="600px">
      <el-form ref="shipForm" :model="shipForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>

        <el-form-item label="订单编号" prop="shipForm.orderCode">
          <span>{{shipForm.orderCode}}</span>
        </el-form-item>
        <el-form-item label="商品名称" prop="shipForm.goodsName">
          <span>{{ shipForm.goodsName }}</span>
        </el-form-item>
        <el-form-item label="收货人" prop="shipForm.receiverName">
          <span>{{ shipForm.receiverName }}</span>
        </el-form-item>
        <el-form-item label="手机" prop="shipForm.receiverMobile">
          <span>{{ shipForm.receiverMobile }}</span>
        </el-form-item>
        <el-form-item label="收件人地址" prop="shipForm.receiverAddress">
          <span>{{ shipForm.receiverAddress }}</span>
        </el-form-item>
        <el-form-item label="发货方" prop="shipper">
          <el-select v-model="shipForm.shipper">
            <el-option label="爱能" value="0" :selected="true"></el-option>
            <el-option label="其他仓库" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司" prop="shipperCode" v-show="shipForm.shipper == '0'">
          <el-select v-model="shipForm.shipperCode" placeholder="请选择快递公司">
            <el-option label="顺丰速运" value="SF" :selected="true"></el-option>
            <!-- <el-option label="中通快递" value="ZTO"></el-option> -->
            <el-option label="圆通速递" value="YTO"></el-option>
            <el-option label="邮政快递包裹" value="YZPY"></el-option>
            <el-option label="邮政国内标快" value="YZBK"></el-option>
            <!-- <el-option label="韵达速递" value="YD"></el-option> -->
            <!-- <el-option label="EMS" value="EMS"></el-option> -->
            <!-- <el-option label="德邦快递" value="DBL"></el-option> -->
            <!-- <el-option label="宅急送" value="ZJS"></el-option> -->
            <!-- <el-option label="TNT快递" value="TNT"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="邮费支付方式" prop="payType" v-show="shipForm.shipper == '0'">
          <el-select v-model="shipForm.payType" placeholder="请选邮费支付方式">
            <el-option label="现付" value="1"></el-option>
            <el-option label="到付" value="2"></el-option>
            <el-option label="月结" value="3"></el-option>
            <el-option label="第三方支付" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递类型" prop="expType" v-show="shipForm.shipper == '0'">
          <el-select v-model="shipForm.expType" placeholder="请选快递类型">
            <el-option label="标准快件" value="1"></el-option>
            <el-option label="顺丰特惠" value="2"></el-option>
            <el-option label="顺丰物流普运" value="13"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子母件个数" prop="quantity" v-show="shipForm.shipper == '0'">
          <el-input-number v-model="shipForm.quantity" placeholder="1" :min="1">
            <!-- <template slot="append">分</template> -->
          </el-input-number>
        </el-form-item>
        <el-form-item label="物流单号" prop="shipSn" v-show="(shipForm.shipperCode == 'YTO' && shipForm.payType == 2) || shipForm.shipper == '1'">
          <el-input ref="content" v-model.trim="shipForm.shipSn"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateElectronicSurface" v-show="shipForm.shipper == '0'">生成电子面单</el-button>
        <el-button type="primary" @click="confirmDelivery" v-show="shipForm.shipper == '1'">确认发货</el-button>
      </div>
    </el-dialog>

    <!-- 发货对话框 -->
    <!-- <el-dialog title="发货" :visible.sync="shipDialogVisible" width="600px">
      <el-form ref="shipForm" :model="shipForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="快递公司" prop="shipChannel">
          <el-input v-model="shipForm.shipChannel"></el-input>
        </el-form-item>
        <el-form-item label="快递编号" prop="shipSn">
          <el-input v-model="shipForm.shipSn"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip">确定</el-button>
      </div>
    </el-dialog> -->

    <!-- 退款对话框 -->
    <el-dialog title="退款" :visible.sync="refundDialogVisible" width="600px">
      <el-form ref="refundForm" :model="refundForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="积分" prop="refundMoney">
          <el-input v-model="refundForm.refundIntegral" :readonly="true"></el-input>
        </el-form-item>
        <el-form-item label="爱币" prop="refundMoney">
          <el-input v-model="refundForm.refundMoney" :readonly="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.el-form-item {
  margin-bottom: 20px;
}
</style>

<script>
import {
  listOrder,
  listTotalOrder,
  shipOrder,
  refundOrder,
  detailOrder,
  queryUnShipOrderNum,
  insertRemark
} from '@/api/order'
import { generateSurface, confirmDelivery } from '@/api/express'

const statusMap = {
  101: '未付款',
  102: '用户取消',
  103: '系统取消',
  201: '已付款',
  202: '申请退款',
  203: '已退款',
  301: '已发货',
  401: '用户收货',
  402: '系统收货',
  501: '用户评价',
  502: '用户追评'
}

export default {
  name: 'Order',
  data() {
    return {
      unShipOrder: 0,
      dialogFormVisibles: false,
      remark: undefined,
      list: undefined,
      total: undefined,
      listLoading: true,
      options: [
        {
          value: '201',
          label: '已付款'
        },
        {
          value: '202',
          label: '申请退款'
        },
        {
          value: '203',
          label: '已退款'
        },
        {
          value: '301',
          label: '已发货'
        },
        {
          value: '401',
          label: '用户收货'
        },
        {
          value: '402',
          label: '系统收货'
        },
        {
          value: '501',
          label: '用户评价'
        },
        {
          value: '502',
          label: '用户追评'
        }
      ],
      editForm: {
        id: undefined,
        rowId: undefined,
        remark: undefined
      },
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        goodsId: undefined,
        name: undefined,
        orderStatusArray: [],
        value: '',
        sort: 'add_time',
        order: 'desc',
        timeInterval: [
          new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000 * 30,
          new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000)
        ]
      },
      statusMap,
      LODOP: '',
      orderDialogVisible: false,
      orderDetail: {
        order: {},
        user: {},
        orderGoods: [],
        mechanism: {}
      },
      nickname: '',
      shipForm: {
        // orderId: undefined,
        // shipChannel: undefined,
        // shipSn: undefined,
        receiverName: undefined,
        receiverId: undefined,
        receiverMobile: undefined,
        receiverProvinceName: undefined,
        receiverCityName: undefined,
        receiverExpAreaName: undefined,
        receiverAddress: undefined,
        goodsName: undefined,
        orderCode: undefined,
        shipper: '0',
        shipperCode: 'SF',
        payType: '1',
        expType: '2',
        quantity: '1'
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '前天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      shipDialogVisible: false,
      refundForm: {
        orderId: undefined,
        recordSn: undefined,
        refundIntegral: undefined,
        refundMoney: undefined
      },
      refundDialogVisible: false,
      downloadLoading: false
    }
  },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status]
    }
  },
  created() {
    this.getList()
    this.queryUnShipOrderNum()
  },
  mounted: function() {
    this.interval = setInterval(this.queryUnShipOrderNum, 30000)
  },
  beforeDestroy: function() {
    clearInterval(this.interval)
  },
  methods: {
    getList() {
      this.listLoading = true
      if (this.listQuery.timeInterval != null) {
        this.listQuery.start = this.listQuery.timeInterval[0]
        this.listQuery.end = this.listQuery.timeInterval[1]
      } else {
        this.listQuery.start = ''
        this.listQuery.end = ''
      }
      listOrder(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(response => {
          this.list = []
          this.total = 0
          this.listLoading = false
          this.$message({
            message: response.data.errmsg,
            type: 'warning'
          })
        })
    },

    handleClick(row) {
      this.dialogFormVisibles = true
      this.editForm.id = row.id
    },
    exchangeData() {
      insertRemark(this.editForm)
        .then(response => {
          detailOrder(this.editForm.rowId).then(response => {
            this.orderDetail = response.data.data
            if (this.orderDetail.order.mechanismType) {
              this.nickname = this.orderDetail.mechanismUser.username
            } else {
              this.nickname = this.orderDetail.user.nickname
            }
            this.editForm.remark = ''
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '编辑失败，稍后再试'
          })
        })
      this.dialogFormVisibles = false
    },
    queryUnShipOrder() {
      this.listQuery.value = '201'
      this.getList()
      this.unShipOrder = 0
    },
    queryUnShipOrderNum() {
      var status = '201'
      queryUnShipOrderNum(status)
        .then(response => {
          this.unShipOrder = response.data.data.unShipOrder
          var daiFaNum = response.data.data.daiFaNum
          // var refundNum = response.data.data.refundNum
          if (daiFaNum > 0) {
            const audio = document.getElementById('audio')
            audio.play()
          }
          // if (refundNum > 0) {
          //   const audio = document.getElementById('audio')
          //   audio.play()
          // }
        })
        .catch(() => {
          this.unShipOrder = 0
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleDetail(row) {
      this.editForm.rowId = row.id
      detailOrder(row.id).then(response => {
        this.orderDetail = response.data.data
        if (this.orderDetail.order.mechanismType) {
          this.nickname = this.orderDetail.mechanismUser.username
        } else {
          this.nickname = this.orderDetail.user.nickname
        }
      })
      this.orderDialogVisible = true
    },
    handleShip(row) {
      var noiseChar = '#$%^&_+-=`[]{};\':"\\|,./<>?\n\r～！＠＃＄％＆＊·‘’¥——＿＋－＝｀｛｝；＇：＂＼｜，．／“”　'
      var goodChar = ''
      detailOrder(row.id).then(response => {
        this.orderDetail = response.data.data
        this.shipForm.receiverName = this.orderDetail.order.consignee
        this.shipForm.receiverId = this.orderDetail.order.userId
        this.shipForm.receiverMobile = this.orderDetail.order.mobile
        this.shipForm.receiverAddress = this.orderDetail.order.address
        this.shipForm.goodsName = this.orderDetail.orderGoods[0].goodsName
        for (var i = 0; i < noiseChar.length; i++) {
          var oneChar = noiseChar.charAt(i)
          var towChar = goodChar
          this.shipForm.goodsName = this.shipForm.goodsName.replace(oneChar, towChar)
        }
        this.shipForm.orderCode = this.orderDetail.order.orderSn
      })

      this.shipDialogVisible = true
      this.$nextTick(() => {
        this.$refs['shipForm'].clearValidate()
      })
    },
    orderDialogsee() {
      this.CreatePrintPage()
      window.location.reload()
      /*global LODOP*/ /*eslint no-undef: "error"*/ LODOP.PREVIEW()
      return false
    },
    orderDialogOut() {
      this.CreatePrintPage()
      window.location.reload()
      LODOP.PRINT()
      return false
    },
    // handleShip(row) {
    //   this.shipForm.orderId = row.id
    //   this.shipForm.shipChannel = row.shipChannel
    //   this.shipForm.shipSn = row.shipSn

    //   this.shipDialogVisible = true
    //   this.$nextTick(() => {
    //     this.$refs['shipForm'].clearValidate()
    //   })
    // },
    CreatePrintPage() {
      var LODOP = /*global getLodop*/ /*eslint no-undef: "error"*/ getLodop()
      // LODOP.PRINT_INITA(10, 10, 754, 453, '打印控件功能演示_Lodop功能_多页文档')
      LODOP.SET_PRINT_STYLEA(2, 'FontSize', 18)
      LODOP.SET_PRINT_STYLEA(2, 'Bold', 1)
      var Output = document.getElementById('orderDialog')
      var newContent = Output.innerHTML
      document.body.innerHTML = newContent
      LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', document.getElementsByTagName('html')[0].innerHTML)
      var cont = LODOP.GET_PRINTER_COUNT()
      for (var i = 0; i < cont; i++) {
        var strPrinterName = LODOP.GET_PRINTER_NAME(i)
        if (strPrinterName === 'HP DJ 5000 series') {
          LODOP.SET_PRINTER_INDEXA(strPrinterName)
        }
      }
    },

    confirmShip() {
      this.$refs['shipForm'].validate(valid => {
        if (valid) {
          shipOrder(this.shipForm).then(response => {
            this.shipDialogVisible = false
            this.$notify({
              title: '成功',
              message: '确认发货成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    generateElectronicSurface() {
      if (this.shipForm.shipperCode === 'YTO' && this.shipForm.payType === '2') {
        if (this.shipForm.shipSn === null || this.shipForm.shipSn === '' || this.shipForm.shipSn === undefined) {
          this.$message.info('物流单号不能为空')
          this.$refs.content.focus()
        } else {
          const loading = this.$loading({
            lock: true,
            text: '正在生成电子面单',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.shipDialogVisible = false
          generateSurface(this.shipForm).then(response => {
            loading.close()
            this.getList()
            var data = response.data
            if (data.errno === 0) {
              this.$notify({
                title: '成功',
                message: '发货成功',
                type: 'success'
              })
              var jsondata = JSON.parse(data.data)
              var newWindow = window.open('', '_blank')
              newWindow.document.write(jsondata['PrintTemplate'])
              setTimeout(() => {
                newWindow.print()
              }, 100)
            } else {
              this.$notify({
                title: '失败',
                message: '发货失败，请重试',
                type: 'error'
                // duration: 2000
              })
            }
          })
          // setTimeout(() => {
          //   loading.close()
          // }, 2000)
        }
      } else {
        const loading = this.$loading({
          lock: true,
          text: '正在生成电子面单',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.shipDialogVisible = false
        generateSurface(this.shipForm).then(response => {
          loading.close()
          this.getList()
          var data = response.data
          if (data.errno === 0) {
            this.$notify({
              title: '成功',
              message: '发货成功',
              type: 'success'
            })
            var jsondata = JSON.parse(data.data)
            if (jsondata.SubCount > 0) {
              var newWindows = window.open('', '_blank')
              newWindows.document.write(jsondata['PrintTemplate'])
              newWindows.document.writeln("<span style='line-height:2px;'></span><br><br>")
              for (var i = 0; i < jsondata.SubCount; i++) {
                newWindows.document.write(jsondata.SubPrintTemplates[i])
                newWindows.document.writeln("<span style='line-height:2px;'></span><br><br>")
              }
              setTimeout(() => {
                newWindows.print()
              }, 200)
            } else {
              var newWindow = window.open('', '_blank')
              newWindow.document.write(jsondata['PrintTemplate'])
              setTimeout(() => {
                var LODOP = getLodop()
                // LODOP.PRINT_INITA(10, 10, 754, 453, '打印控件功能演示_Lodop功能_多页文档')
                LODOP.SET_PRINT_STYLEA(2, 'FontSize', 18)
                LODOP.SET_PRINT_STYLEA(2, 'Bold', 1)
                LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', jsondata['PrintTemplate'])
                var cont = LODOP.GET_PRINTER_COUNT()
                for (var i = 0; i < cont; i++) {
                  var strPrinterName = LODOP.GET_PRINTER_NAME(i)
                  if (strPrinterName === 'HPRT HLP106S') {
                    LODOP.SET_PRINTER_INDEXA(strPrinterName)
                  }
                }
                window.location.reload()
                LODOP.PREVIEW()
              }, 100)
            }
          } else {
            this.$notify({
              title: '失败',
              message: '发货失败，请重试',
              type: 'error'
              // duration: 2000
            })
          }
        })
        // setTimeout(() => {
        //   loading.close()
        // }, 2000)
      }
    },
    confirmDelivery() {
      if (this.shipForm.shipSn === null || this.shipForm.shipSn === '' || this.shipForm.shipSn === undefined) {
        this.$message.info('物流单号不能为空')
        this.$refs.content.focus()
      } else {
        confirmDelivery(this.shipForm).then(response => {
          this.getList()
          var data = response.data
          if (data.errno === 0) {
            this.shipDialogVisible = false
            this.$notify({
              title: '成功',
              message: '发货成功',
              type: 'success'
            })
          } else {
            this.$notify({
              title: '失败',
              message: '发货失败，请重试',
              type: 'error'
              // duration: 2000
            })
          }
        })
      }
    },
    handleRefund(row) {
      this.refundForm.orderId = row.id
      this.refundForm.recordSn = this.createRecordSn()
      this.refundForm.refundIntegral = row.actualIntegral
      this.refundForm.refundMoney = row.actualPrice
      this.refundDialogVisible = true
      this.$nextTick(() => {
        this.$refs['refundForm'].clearValidate()
      })
    },
    confirmRefund() {
      this.$refs['refundForm'].validate(valid => {
        if (valid) {
          refundOrder(this.refundForm).then(response => {
            this.refundDialogVisible = false
            this.$notify({
              title: '成功',
              message: '确认退款成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDownload() {
      import('@/vendor/Export2Excel').then(excel => {
        if (this.listQuery.timeInterval.length > 0) {
          this.listQuery.start = this.listQuery.timeInterval[0]
          this.listQuery.end = this.listQuery.timeInterval[1]
        }
        listTotalOrder(this.listQuery).then(response => {
          const tHeader = [
            '订单ID',
            '订单编号',
            '用户ID',
            '订单状态',
            '实付积分',
            '实付爱币',
            '是否删除',
            '收货人',
            '收货联系电话',
            '收货地址',
            '商品ID',
            '规格ID',
            '商品名称',
            '规格',
            '品牌商',
            '品牌商ID',
            '类目',
            '类目ID',
            '数量',
            '消费/赠送',
            '爱币',
            '消费/赠送',
            '积分',
            '备注'
          ]
          const filterVal = [
            'id',
            'orderSn',
            'userId',
            'orderStatus',
            'actualIntegral',
            'actualPrice',
            'deleted',
            'consignee',
            'mobile',
            'address',
            'goodsId',
            'productId',
            'goodsName',
            'specifications',
            'name',
            'brandId',
            'categoryName',
            'categoryId',
            'number',
            'priceFlag',
            'price',
            'integralFlag',
            'integral',
            'remark'
          ]
          const list = response.data.data.items
          for (var i = 0; i < list.length; i++) {
            if (list[i].orderStatus === 101) list[i].orderStatus = '未付款'
            else if (list[i].orderStatus === 102) list[i].orderStatus = '用户取消'
            else if (list[i].orderStatus === 103) list[i].orderStatus = '系统取消'
            else if (list[i].orderStatus === 201) list[i].orderStatus = '已付款'
            else if (list[i].orderStatus === 202) list[i].orderStatus = '申请退款'
            else if (list[i].orderStatus === 203) list[i].orderStatus = '已退款'
            else if (list[i].orderStatus === 301) list[i].orderStatus = '已发货'
            else if (list[i].orderStatus === 401) list[i].orderStatus = '用户收货'
            else if (list[i].orderStatus === 402) list[i].orderStatus = '系统收货'
            else if (list[i].orderStatus === 501) list[i].orderStatus = '用户评价'
            else if (list[i].orderStatus === 502) list[i].orderStatus = '用户追评'

            if (list[i].deleted === false) list[i].deleted = '否'
            else if (list[i].deleted === true) list[i].deleted = '是'

            if (list[i].priceFlag === 1) list[i].priceFlag = '消费'
            else if (list[i].priceFlag === 2) list[i].priceFlag = '赠送'

            if (list[i].integralFlag === 1) list[i].integralFlag = '消费'
            else if (list[i].integralFlag === 2) list[i].integralFlag = '赠送'
          }
          excel.export_json_to_excel2(tHeader, list, filterVal, '订单信息')
          this.downloadLoading = false
        })
      })
    },
    createRecordSn() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var ss = date.getMilliseconds()
      if (ss < 10) {
        ss = '00' + ss
      } else if (ss < 100) {
        ss = '0' + ss
      }
      return Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString()
    }
  }
}
</script>
